package com.hsnn.medstgmini.sys.dao.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.dao.impl.BaseHibernateDAO;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.model.Whether;
import com.hsnn.medstgmini.sys.dao.SysUserDao;
import com.hsnn.medstgmini.sys.model.SysPrivilege;
import com.hsnn.medstgmini.sys.model.SysRole;
import com.hsnn.medstgmini.sys.model.SysSequence;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.MD5Util;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;

/**
 * @category 用户管理
 * @author 蔡春龙
 * @date 2015年6月15日
 */
@Repository
public class SysUserDaoImpl extends BaseHibernateDAO implements SysUserDao {
	private static final Logger log = Logger.getLogger(SysUserDaoImpl.class);

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	@Autowired
	private HibernateSqlUtil dao;

	/**
	 * @category 根据用户名查询用户
	 * @date 2015年6月15日
	 * @param username
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public SysUser getUserByUsername(String username) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		criteria.add(Restrictions.eq("username", username));
		List<SysUser> users = criteria.list();
		if (users == null || users.isEmpty()) {
			log.error("user '" + username + "' not found...");
			return null;
		} else {
			return (SysUser) users.get(0);
		}
	}

	/**
	 * @category 根据当前用户获取根父级用户
	 * @date 2015年6月16日
	 * @param currUser
	 * @return
	 */
	public SysUser getRootFatherUser(SysUser currUser) {
		Session session = sessionFactory.getCurrentSession();
		if (currUser != null && currUser.getMain() == Whether.no.getKey()) {
			Criteria criteria = session.createCriteria(SysUser.class);
			criteria.add(Restrictions.eq("id", currUser.getPid()));
			criteria.add(Restrictions.eq("status", Status.enabled.getKey()));
			SysUser father = (SysUser) criteria.uniqueResult();
			if (father != null) {
				if (father.getMain() == Whether.no.getKey()) {
					return getRootFatherUser(father);
				} else {
					return father;
				}
			}
		}
		return null;
	}

	/**
	 * @category 保存登陆ip，登陆时间，登陆次数等信息
	 * @date 2015年6月15日
	 * @param user
	 */
	public void saveLoginInfo(SysUser user) {
		Session session = sessionFactory.getCurrentSession();
		if (user != null) {
			Integer count = user.getLoginCount();
			if (count == null) {
				count = 1;
			} else {
				count++;
			}
			user.setLoginCount(count);
			user.setLoginTime(new Date());
			session.saveOrUpdate(user);
			session.flush();
		}

	}

	/**
	 * @category 中心分页查询用户列表
	 * @date 2015年6月16日
	 * @param user
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getZxUserList(Pagination page, SysUser user) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		criteria.add(Restrictions.eq("main", Whether.yes.getKey()));
		
		if (user != null) {
			String name = user.getName();
			if (StringUtils.isNotBlank(name)) {
				criteria.add(Restrictions.like("name", "%" + name + "%"));
			}
			String username=user.getUsername();
			if (StringUtils.isNotBlank(username)) {
				criteria.add(Restrictions.like("username", "%" + username + "%"));
			}
		}
		/*String  username = page.getConditions().get("username");*/
//		String  type = page.getConditions().get("type");
		String  status = page.getConditions().get("status");
		
		/*if (StringUtils.isNotBlank(username)) {
			criteria.add(Restrictions.eq("username",username));
		}*/
//		if (null != user.getType()) {
//			System.out.println(user.getType());
//			criteria.add(Restrictions.eq("type:", user.getType()));
//		}else{
//			System.out.println("type kye:"+UserType.zx.getKey());
//			criteria.add(Restrictions.ne("type",UserType.zx.getKey()));
//		}
		if (StringUtils.isNotBlank(status)) {
			criteria.add(Restrictions.eq("status:",ParseNumber.toInteger(status)));
		}
		// 查询个数
		criteria.setProjection(Projections.rowCount());
		Long records = (Long) criteria.uniqueResult();
		page.setRecords(records);

		// 查询列表
		criteria.setProjection(null);
		criteria.addOrder(Order.desc("createDateTime"));
		criteria.setFirstResult(page.getFirstResult());
		criteria.setMaxResults(page.getMaxResults());
		List<SysUser> list = criteria.list();
		page.setRows(list);

		return page;
	}

	/**
	 * @category 启用|停用
	 * @param role
	 */
	public void changeStatus(SysUser user) {
		Session session = sessionFactory.getCurrentSession();
		if (user != null) {
			SysUser su = getUserById(user.getId());
			if (su != null) {
				su.setStatus(user.getStatus());
				su.setUpdUser(user.getUpdUser());
				su.setUpdDateTime(new Date());
				session.update(su);
				session.flush();
			}
		}
	}

	/**
	 * @category 批量(启用|停用)
	 * @param list
	 */
	@Override
	public void batchChangeStatus(List<SysUser> list) {
		if (list != null && list.size() > 0) {
			for (SysUser user : list) {
				changeStatus(user);
				writeUserLogSimple(user.getId());
			}
		}
	}

	public void writeUserLogSimple(String userId) {
		StringBuffer hqlLog = new StringBuffer();
		hqlLog.append("insert into sys_user_log  ")
		      .append(" select UUID(),su.* from sys_user su where su.id= :userId ");
		Query queryLog = getSession().createSQLQuery(hqlLog.toString());
		queryLog.setString("userId", userId);
		queryLog.executeUpdate();
		getSession().flush();
	}
	
	/**
	 * @category 根据id查询用户
	 * @date 2015年6月17日
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public SysUser getUserById(String id) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		criteria.add(Restrictions.eq("id", id));
		List<SysUser> list = criteria.list();
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public SysUser getUserByOrgId(String OrgId) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		criteria.add(Restrictions.eq("id", OrgId));
		List<SysUser> list = criteria.list();
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * @category 获取sequence
	 */
	public Long getSequence() {
		Long sequence = 10000000L;
		synchronized (SysSequence.class) {
			Session session = sessionFactory.getCurrentSession();
			Criteria criteria = session.createCriteria(SysSequence.class);
			criteria.add(Restrictions.eq("id", "1"));
			SysSequence ss = (SysSequence) criteria.uniqueResult();
			if (ss == null) {
				ss = new SysSequence();
				ss.setId("1");
				ss.setSequence(sequence.toString());
				session.saveOrUpdate(ss);
				session.flush();
			} else {
				String seq = ss.getSequence();
				if (StringUtils.isNotBlank(seq)) {
					sequence = Long.parseLong(seq);
					sequence++;
					ss.setSequence(sequence.toString());
					session.saveOrUpdate(ss);
					session.flush();
				}
			}
		}
		return sequence;
	}

	/**
	 * @category 中心保存主用户信息
	 * @date 2015年6月14日
	 * @param user
	 */
	public void zxSaveUser(int opType, SysUser user, List<SysPrivilege> list) {
		Session session = sessionFactory.getCurrentSession();
		if (user != null && user.getRole() != null) {
			// 保存角色信息
			if (opType == Constants.OP_TYPE_EDIT) {
				SysUser oldUser = getUserById(user.getId());
				oldUser.setUpdUser(user.getUpdUser());
				oldUser.setStatus(user.getStatus());
				oldUser.setPassword(user.getPassword());
				oldUser.setRemark(user.getRemark());
				oldUser.setLocked(user.getLocked());
				oldUser.setPhone(user.getPhone());
				oldUser.setEmail(user.getEmail());
				oldUser.setPasswordExpired(user.getPasswordExpired());
				session.update(oldUser);
			} else if (opType == Constants.OP_TYPE_ADD) {
				SysUser oldUser = getUserById(user.getId());
				if (oldUser != null) {
					throw new MSException("此用户已有帐号，帐号：" + oldUser.getUsername());
				}
				user.setCreateDateTime(new Date());
				user.setAcctEnabled(Whether.yes.getKey());
				session.save(user);
			}

			// 删除用户角色
			if (StringUtils.isNotBlank(user.getRole().getId())) {
				String sql = "delete from sys_user_role where user_id=:userId";
				SQLQuery query = session.createSQLQuery(sql);
				query.setString("userId", user.getId());
				query.executeUpdate();
			}

			// 保存用户角色
			if (StringUtils.isNotBlank(user.getRole().getId())) {
				String sql = "insert into sys_user_role values (:userId, :roleId)";
				SQLQuery query = session.createSQLQuery(sql);
				query.setString("userId", user.getId());
				query.setString("roleId", user.getRole().getId());
				query.executeUpdate();
			}

			// 删除当前用户所有附加权限
			String sql = "delete from sys_user_privilege where user_id=:userId ";
			SQLQuery query = session.createSQLQuery(sql);
			query.setString("userId", user.getId());
			query.executeUpdate();

			// 保存当前用户附加权限
			if (list != null) {
				for (SysPrivilege sp : list) {
					sql = "insert into sys_user_privilege values (:userId, :privilegeId)";
					query = session.createSQLQuery(sql);
					query.setString("userId", user.getId());
					query.setString("privilegeId", sp.getId());
					query.executeUpdate();
				}
			}
			session.flush();
		}
	}

	/**
	 * @category 中心、医疗机构、企业查询子用户列表
	 * @date 2015年6月18日
	 * @param page
	 * @param loginUser当前登人
	 * @param user查询条件
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getSubUserList(Pagination page, SysUser loginUser,
			SysUser user) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		criteria.add(Restrictions.eq("main", Whether.no.getKey()));
		criteria.add(Restrictions.eq("pid", loginUser.getId()))
		.add(Restrictions.eq("type", loginUser.getType()));

		if (user != null) {
			String name = user.getName();
			if (StringUtils.isNotBlank(name)) {
				criteria.add(Restrictions.like("name", "%" + name + "%"));
			}
			Integer status = user.getStatus();
			if (status!=null) {
				criteria.add(Restrictions.eq("status",status));
			}
			
			String userName = user.getUsername();
			if (StringUtils.isNotBlank(userName)) {
				criteria.add(Restrictions.eq("username",userName));
			}
		}

		// 查询个数
		criteria.setProjection(Projections.rowCount());
		Long records = (Long) criteria.uniqueResult();
		page.setRecords(records);

		// 查询列表
		criteria.setProjection(null);
		criteria.addOrder(Order.desc("createDateTime"));
		criteria.setFirstResult(page.getFirstResult());
		criteria.setMaxResults(page.getMaxResults());
		List<SysUser> list = criteria.list();
		page.setRows(list);

		return page;
	}

	/**
	 * @category 中心修改密码
	 * @date 2015年6月19日
	 * @param id
	 * @param password
	 */
	public void changePassword(String id, String password) {
		Session session = sessionFactory.getCurrentSession();
		if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(password)) {
			SysUser user = getUserById(id);
			if (user != null) {
				user.setPassword(password);
				session.saveOrUpdate(user);
				session.flush();
			}
		}
	}


	@Override
	public void saveZUser(SysUser user,String updUser) {
		Session session = sessionFactory.getCurrentSession();
		String sql = "update sys_user  set name = :name,email=:email,phone=:phone,remark=:remark,upd_datetime=:updDatetime,upd_user=:updUser,body_height=:bodyHeight,weight=:weight,waist=:waist,acct_expired=:acctExpired  where id = :id";
		Query query = session.createSQLQuery(sql);
		query.setString("id", user.getId());
		query.setString("name", user.getName());
		query.setString("email", user.getEmail());
		query.setString("phone", user.getPhone());
		query.setString("remark", user.getRemark());
		query.setTimestamp("updDatetime", new Date());
		query.setString("updUser",updUser);
		query.setFloat("bodyHeight", user.getBodyHeight());
		query.setFloat("weight", user.getWeight());
		query.setFloat("waist", user.getWaist());
		query.setDate("acctExpired", user.getAcctExpired());
		query.executeUpdate();
		session.flush();
	}
	
	/**
	 * @category 根据机构id及主账户查询父级id
	 * @author 韩守松
	 * @date   2015年10月16日
	 * @param  @return
	 */
	public String getPidId(String orgId,Integer main) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer hql = new StringBuffer();
		hql.append("select su.pid from SysUser su where su.main = :main ");
		Query query = session.createQuery(hql.toString());
		//query.setString("orgId", orgId);
		query.setInteger("main", main);
		return query.list().get(0).toString();
	}


	@Override
	public Pagination getHospInfoList(Pagination page) {
		String areaId = page.getConditions().get("areaId");
		String hospCode = page.getConditions().get("hospCode");
		String hospName = page.getConditions().get("hospName");
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT  sh.hosp_id hospId, ")
		.append("         sh.hosp_code hospCode, ")
		.append("         sh.hosp_name hospName, ")
		.append("         sh.org_code orgCode, ")
		.append("         sh.hosp_classify hospClassify, ")
		.append("         D.dic_name hospLevelId, ")
		.append("         da.ar_fullname arfullname, ")
		.append("         C.dic_name hospTypeName, ")
		.append("         sh.status status   ")
		.append(" from std_hospinfo sh  ")
		.append("     JOIN dic_area da  ON sh.area_id = da.area_id  ")
		.append("     LEFT JOIN (select id,org_id from sys_user where type=4 and main=1) su on su.org_id=sh.hosp_id ")
		.append("     LEFT JOIN dic_sysdic C  ON sh.hosp_classify = C.dic_code and C.classify_code = '113' ")
		.append("     LEFT JOIN dic_sysdic D  ON sh.hosp_level_id = D.dic_code and D.classify_code = '002' ")
		.append("     where su.org_id is null and sh.status =1 ");
		if(StringUtils.isNotBlank(areaId)){
			sql.append("  and da.area_id like :areaId ");
			page.getConditions().put("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(hospCode)){
			sql.append(" and sh.hosp_code=:hospCode ");
		}
		if(StringUtils.isNotBlank(hospName)){
			sql.append(" and sh.hosp_name like :hospName ");
			page.getConditions().put("hospName", "%"+hospName+"%");
		}
		return dao.getSqlPageMapList(sql.toString(), page.getConditions(), page);
	}


	@Override
	public Pagination getCompInfoList(Pagination page) {
		String areaId = page.getConditions().get("areaId");
		String compType = page.getConditions().get("compType");
		String compRegId = page.getConditions().get("compRegId");//企业注册类型
		String compCode = page.getConditions().get("compCode");
		String compName = page.getConditions().get("compName");
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT A.comp_id compId, ")
		   .append("      A.comp_code compCode, ")
		   .append("      A.comp_name compName, ")
		   .append("      A.org_code orgCode, ")
		   .append("      A.comp_spel_code compSpelCode, ")
		   .append("      A.comp_type compType, ")
		   .append("      A.area_id areaId, ")
		   .append("      A.comp_reg_id compRegId, ")
		   .append("      A.status status, ")
		   .append("      A.upd_datetime updDatetime, ")
		   .append("      B.ar_fullname arFullname, ")
		   .append("      C.comp_reg_name compRegName  ")
		   .append("  FROM ")
		   .append("      std_compinfo A  ")
		   .append("  LEFT JOIN dic_area B on A.area_id = B.area_id  ")
		   .append("  LEFT JOIN (select id,org_id from sys_user where  main=1 and type="+compType+" ) su on su.org_id=A.comp_id  ")
		   .append("  LEFT JOIN dic_comptype C   on C.comp_reg_id = A.comp_reg_id  ")
		   .append("  where A.comp_type =:compType and A.status=1 and su.org_id is null  ");
		page.getConditions().put("compType",compType.equals("2")?"1":(compType.equals("3")?"2":""));
		if(StringUtils.isNotBlank(areaId)){
			sql.append(" and B.area_id like :areaId ");
			page.getConditions().put("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(compRegId)){
			sql.append(" and A.comp_reg_id = :compRegId ");
		}
		if(StringUtils.isNotBlank(compCode)){
			sql.append(" and A.comp_code=:compCode ");
		}
		if(StringUtils.isNotBlank(compName)){
			sql.append(" and A.comp_name like :compName ");
			page.getConditions().put("compName", "%"+compName+"%");
		}
		return dao.getSqlPageMapList(sql.toString(), page.getConditions(), page);
	}

	
	@Override
	public Pagination getStdExpertList(Pagination page) {
		Map<String,String> params = new HashMap<String,String>();
		String expSkills = page.getConditions().get("expSkills");
		String name = page.getConditions().get("name");
		String companyId = page.getConditions().get("companyId");
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT s.expert_id expertId,s.expert_code expertCode,s.name name, s.exp_skills expSkills,  ")
		.append(" s.sex sex,   DATE_FORMAT(s.birthday,'%Y-%m-%d') birthday,s.handphone handphone,s.company_id companyId, ")
		.append(" s.position position,s.status status FROM std_expert s ")
		.append(" LEFT JOIN ( select id,org_id from sys_user where type=5 and main=1 ) su on su.org_id = s.expert_id ")
		.append(" WHERE su.org_id is null and s.status=1 ");
		if(StringUtils.isNotBlank(expSkills)){
			sql.append(" and s.exp_skills like :expSkills ");
			params.put("expSkills", "%"+expSkills.trim()+"%");
		}
		if(StringUtils.isNotBlank(name)){
			sql.append(" and s.name like :name ");
			params.put("name", "%"+name.trim()+"%");
		}
		if(StringUtils.isNotBlank(companyId)){
			sql.append(" and s.company_id like :companyId ");
			params.put("companyId", "%"+companyId.trim()+"%");
		}
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}


	@Override
	public Pagination getStdHealthbureauList(Pagination page) {
		String heaBurName = page.getConditions().get("heaBurName");
		String heaBurCode = page.getConditions().get("heaBurCode");
		String areaId = page.getConditions().get("areaId");
		StringBuffer sql = new StringBuffer()
		.append(" SELECT h.hea_bur_id        heaBurId, ")
		.append("        h.hea_bur_code      heaBurCode, ")
		.append("        h.hea_bur_name      heaBurName, ")
		.append("        h.contact_name      contactName, ")
		.append("        h.contact_telephone contactTelephone, ")
		.append("        B.ar_fullname       arFullname ")
		.append(" FROM   std_healthbureau h ")
		.append("        LEFT JOIN dic_area B ")
		.append("               ON h.area_id = B.area_id ")
		.append("        LEFT JOIN (SELECT id, ")
		.append("                          org_id ")
		.append("                   FROM   sys_user ")
		.append("                   WHERE  type = 6 ")
		.append("                          AND main = 1) su ")
		.append("               ON su.org_id = h.hea_bur_id ")
		.append(" WHERE  su.org_id IS NULL and h.status=1 ");
		
		if(StringUtils.isNotBlank(areaId)){
			sql.append(" and B.area_id like :areaId ");
			page.getConditions().put("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(heaBurName)){
			sql.append(" and h.hea_bur_name like :heaBurName ");
			page.getConditions().put("heaBurName", "%"+heaBurName+"%");
		}
		if(StringUtils.isNotBlank(heaBurCode)){
			sql.append(" and h.hea_bur_code = :heaBurCode ");
		}
		return dao.getSqlPageMapList(sql.toString(), page.getConditions(), page);
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<SysRole> getSysRoleListByType(String id) {
		Criteria criteria = getSession().createCriteria(SysRole.class);
		criteria.add(Restrictions.eq("pid", id))
		.add(Restrictions.eq("status", Constants.ENABLED))
		.add(Restrictions.eq("main", Constants.ISNOT_MAIN))
		.add(Restrictions.isNull("boundId"));
		List<SysRole> list = (List<SysRole>)criteria.list();
		if (list != null && !list.isEmpty()) {
			return list;
		}
		return null;
	}

	@Override
	public Boolean addSysUserRole(String userId, String roleId,Date updTime) {
		Session session = getSession();
		String selectRole = "select * from sys_user_role where user_id=:userId";
		Query query = session.createSQLQuery(selectRole);
		query.setString("userId",userId);
		Object[] obj = (Object[]) query.uniqueResult();
		if(obj!=null){//说明已经有用户角色关系了，则删除用户角色关系
			if(roleId.equals(obj[1])){
				return false;
			}else{
				String deleteSql = " delete from sys_user_role where user_id=:userId ";
				SQLQuery query3 = session.createSQLQuery(deleteSql);
				query3.setString("userId", userId)
				.executeUpdate();
				session.flush();
				session.clear();
			}
	
		}
		String roleSql = " INSERT INTO sys_user_role(user_id,role_id) values(:userId,:roleId) ";
		SQLQuery query2 = session.createSQLQuery(roleSql);
		query2.setString("userId", userId)
		.setString("roleId", roleId)
		.executeUpdate();
		session.flush();
		session.clear();
		//TODO 用户角色表日志
		return true;
	}

	@Override
	public List<String> getRolePrivilegeList(String roleId) {
		String rolePrivilegeSql = " SELECT privilege_id from sys_role_privilege WHERE role_id ='"+roleId+"'";
		Query rolePrivilegeQuery = getSession().createSQLQuery(rolePrivilegeSql);
		@SuppressWarnings("unchecked")
		List<String> list = rolePrivilegeQuery.list();
		return list.size()>0?list:null;
	}

	@Override
	public Boolean addPrivilege(String userId, List<String> list,Date updTime) {
		StringBuffer values = new StringBuffer();
		Session session = getSession();
		//删除用户权限关系
		String deleteSql = " delete from sys_user_privilege where user_id=:userId ";
		SQLQuery query3 = session.createSQLQuery(deleteSql);
		query3.setString("userId", userId)
		.executeUpdate();
		session.flush();
		session.clear();
		if(list!=null && list.size()>0){
			for(int i =0;i<list.size();i++){
				values.append("('"+userId+"','0','"+list.get(i).toString()+"'),");
			}
			String value =values.substring(0, values.length()-1);
			String privilegeSql = " INSERT INTO sys_user_privilege(user_id,type,privilege_id) values "+value;
			SQLQuery query2 = session.createSQLQuery(privilegeSql);
			int count = query2.executeUpdate();
			session.flush();
			session.clear();
			//TODO 用户权限表日志
			return count>0?true:false;
		}
		return false;
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<Object> getExpSkillsList() {
		String sql =" select exp_skills from std_expert where status=1 and exp_skills is not null";
		Query query = getSession().createSQLQuery(sql.toString());
		List<Object> list =query.list();
		return  (list.size()>0?list:null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getSubUserByzxId(String id) {
		String sql =" select id from sys_user where pid=:id";
		Query query = getSession().createSQLQuery(sql.toString());
		query.setParameter("id", id);
		List<String> list =query.list();
		return  (list.size()>0?list:null);
	}

	
	@Override
	public void writeUserLog(String userId) {
//		StringBuffer hqlLog = new StringBuffer();
//		hqlLog.append("insert into sys_user_log  ")
//		      .append(" select UUID(),su.* from sys_user su where su.id= :userId ");
//		Query queryLog = getSession().createSQLQuery(hqlLog.toString());
//		queryLog.setString("userId", userId);
//		queryLog.executeUpdate();
//		getSession().flush();
	}

	@Override
	public void writeSysUserRoleLog(String userId, Date updTime, String updUser) {
		StringBuffer hqlLog = new StringBuffer();
		hqlLog.append("insert into sys_user_role_log  ")
		      .append(" select UUID(),sur.*,:updUser,:updTime from sys_user_role sur where sur.user_id= :userId ");
		Query queryLog = getSession().createSQLQuery(hqlLog.toString());
		queryLog.setString("userId", userId)
		.setString("updUser", updUser)
		.setParameter("updTime", updTime);
		queryLog.executeUpdate();
		getSession().flush();
	}

	@Override
	public void writeSysUserPrivilegeLog(String userId, Date updTime,String updUser) {
		StringBuffer hqlLog = new StringBuffer();
		hqlLog.append("insert into sys_user_privilege_log  ")
		      .append(" select UUID(),sup.*,:updUser,:updTime from sys_user_privilege sup where sup.user_id= :userId ");
		Query queryLog = getSession().createSQLQuery(hqlLog.toString());
		queryLog.setString("userId", userId)
		.setString("updUser", updUser)
		.setParameter("updTime", updTime);
		queryLog.executeUpdate();
		getSession().flush();
	}

	@Override
	public void writeRolePrivilegeLog(String roleId, Date updTime,String updUser) {
		StringBuffer hqlLog = new StringBuffer();
		hqlLog.append("insert into sys_role_privilege_log  ")
		      .append(" select UUID(),srp.*,:updUser,:updTime from sys_role_privilege srp where srp.role_id= :roleId ");
		Query queryLog = getSession().createSQLQuery(hqlLog.toString());
		queryLog.setString("roleId", roleId)
		.setString("updUser", updUser)
		.setParameter("updTime", updTime);
		queryLog.executeUpdate();
		getSession().flush();
	}

	/**
	 * @category  查询所有用户信息
	 * @author 韩守松
	 * @date   2015年11月11日
	 * @param  @param page
	 * @param  @param user
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getAllZxUserList(Pagination page, SysUser user) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(SysUser.class);
		if (user != null) {
			String name = user.getName();
			if (StringUtils.isNotBlank(name)) {
				criteria.add(Restrictions.like("name", "%" + name + "%"));
			}
		}
		String  username = page.getConditions().get("username");
		String  type = page.getConditions().get("type");
		String  status = page.getConditions().get("status");
		
		if (StringUtils.isNotBlank(username)) {
			criteria.add(Restrictions.eq("username",username));
		}
		if (StringUtils.isNotBlank(type)) {
			criteria.add(Restrictions.eq("type", ParseNumber.toInteger(type)));
		}
		if (StringUtils.isNotBlank(status)) {
			criteria.add(Restrictions.eq("status",ParseNumber.toInteger(status)));
		}
		// 查询个数
		criteria.setProjection(Projections.rowCount());
		Long records = (Long) criteria.uniqueResult();
		page.setRecords(records);

		// 查询列表
		criteria.setProjection(null);
		criteria.addOrder(Order.desc("createDateTime"));
		criteria.setFirstResult(page.getFirstResult());
		criteria.setMaxResults(page.getMaxResults());
		List<SysUser> list = criteria.list();
		page.setRows(list);

		return page;
	}

	/**
	 * @category 根据角色id获取角色信息
	 * @author 韩守松
	 * @date   2015年12月19日
	 * @param  @param roleId
	 * @param  @return
	 */
	public SysRole getSysRoleByRoleId(String roleId) {
		SysRole role = new SysRole();
		StringBuffer hql  = new StringBuffer();
		hql.append(" select name from sys_role where id = :roleId ");
		SQLQuery query = getSession().createSQLQuery(hql.toString());
		query.setParameter("roleId", roleId);
		String name = query.list().get(0).toString();
		role.setName(name);
		return role;
	}
	
	/**
	 * @category 添加医疗机构收货地址
	 * @author wangbing
	 * @date   2015年12月19日
	 * @param  @param roleId
	 * @param  @return
	 */
	@Override
	public void addHospAddress(String userId,String updUser){
		Session session = getSession();
		StringBuffer sql = new StringBuffer()
		.append("insert into pur_hospaddress select :uuid,b.hosp_id,a.id,b.hosp_address,b.hosp_address,a.name,a.phone,1,1,:updDatetime,:updUser ")
		.append(" from sys_user a left join std_hospinfo b on b.hosp_id = a.org_id where a.id = :userId ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("uuid", UUID.randomUUID().toString());
		query.setString("updDatetime", DateUtil.dateTime(new Timestamp(System.currentTimeMillis())));
		query.setString("updUser", updUser);
		query.setString("userId", userId);
		query.executeUpdate();
		session.flush();
	}
	public void addZUser(SysUser user){
		user.setId(UUID.randomUUID().toString());
		user.setOrgId("ZX000001");
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		user.setAcctEnabled(1);
		user.setLocked(0);
		user.setType(1);
		user.setMain(1);
		user.setBussinessShow("1");
		user.setPid("0");
		user.setStatus(1);
		dao.add(user);
	}
	public void saveUserRole(List<String> list, String userId){
		String ursql = "delete from sys_user_role where user_id=:userId";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		dao.executeSql(ursql, params);
		String rpsql = "delete from sys_user_privilege where user_id=:userId";
		dao.executeSql(rpsql, params);
		String inursql = "insert into sys_user_role select :userId,id from sys_role where id in (:ids)";
		params.put("ids", list);
		dao.executeSql(inursql, params);
		StringBuffer inupsql = new StringBuffer();
		inupsql.append("insert into sys_user_privilege")
		.append(" select :userId,t.privilege_id,0,null,null from sys_role_privilege t where t.role_id in (:ids)");
		dao.executeSql(inupsql.toString(), params);
	}
	public void deleteUser(List<String> list){
		String delu = "delete from sys_user where id in (:ids)";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("ids", list);
		dao.executeSql(delu, params);
		String delur = "delete from sys_user_role where user_id in (:ids)";
		dao.executeSql(delur, params);
		String delup = "delete from sys_user_privilege where user_id in (:ids)";
		dao.executeSql(delup, params);
	}
}
